import time

import pygame

from fenrispunk_tools.config import (
    get_background_slug,
    get_frames_per_second,
    get_grid,
    get_icon_file,
    get_screen_size_default,
    get_sprite_length,
    get_tile_file,
    get_window_caption,
)
from fenrispunk_tools.utils.key import get_tile
from fenrispunk_tools.state.GameState import GameState
from fenrispunk_tools.utils.standard import get_datetime_stamp, get_max_dimensions


def load_tiles():
    return pygame.image.load(get_tile_file())


def load_icon():
    return pygame.image.load(get_icon_file())


def main():
    pygame.init()
    pygame.display.set_icon(load_icon())
    pygame.display.set_caption(get_window_caption())

    window = pygame.display.set_mode(get_screen_size_default())

    tiles = load_tiles()
    grid = get_grid()

    screen = pygame.Surface(get_max_dimensions(grid, get_sprite_length()))
    screen.fill(get_background_slug())
    for row in range(len(grid)):
        for col in range(len(grid[row])):
            screen.blit(
                source=tiles,
                dest=(col * get_sprite_length(), row * get_sprite_length()),
                area=get_tile(grid[row][col]),
            )

    state = GameState(True, 0, 0, 1 * get_sprite_length())
    fpsClock = pygame.time.Clock()

    window.blit(screen, dest=state.background.get_position())
    pygame.display.flip()

    while state.running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                state.quit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_p:
                    print("should save now")
                    pygame.image.save(
                        screen,
                        f"fenrispunk_tools_screenshot_{get_datetime_stamp()}.jpeg",
                    )
                if event.key == pygame.K_o:
                    state.background.reset_position()
                if event.key == pygame.K_LEFT:
                    state.background.left()
                if event.key == pygame.K_UP:
                    state.background.up()
                if event.key == pygame.K_RIGHT:
                    state.background.right()
                if event.key == pygame.K_DOWN:
                    state.background.down()

                window.fill(get_background_slug())
                window.blit(screen, dest=state.background.get_position())
                pygame.display.flip()
            fpsClock.tick(get_frames_per_second())
